package cc.rengu.igas.route.core.service.trans;


import cc.rengu.igas.route.common.enums.RouteTxnNumEnum;
import cc.rengu.igas.route.common.enums.SmartRouteRspEnums;
import cc.rengu.igas.route.core.model.ProdInfoBean;
import cc.rengu.igas.route.core.model.RouterReq;
import cc.rengu.igas.route.core.realize.Router;
import cc.rengu.igas.route.core.realize.RouterDataInit;
import cc.rengu.igas.route.core.realize.impl.RouterConfigDataInit;
import cc.rengu.igas.route.core.realize.impl.RouterDataInitMultiDyncData;
import cc.rengu.igas.route.core.realize.impl.RouterDataInitSmartDyncData;
import cc.rengu.igas.route.facade.bean.ProdInfo;
import cc.rengu.igas.route.facade.request.SmartRouteRequest;
import cc.rengu.igas.route.facade.response.SmartRouteResponse;
import cc.rengu.oltp.service.base.RadpService;
import cc.rengu.oltp.service.common.constant.TreeNodeConstant;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.utility.util.BeanUtil;
import cc.rengu.oltp.utility.util.ConvertUtil;
import cc.rengu.oltp.utility.util.XmlTreeUtil;
import cc.rengu.utility.base.StringUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * 智能路由查询服务
 *
 * @author xlz
 * @version 1.0
 * @date 20200320
 */
public class IntelligenceRouterQueryService extends RadpService {
    @Override
    protected int bizInit(String s) {

        try {
            //加载所有的路由规则配置
            RouterDataInit routerDataInit = new RouterConfigDataInit();
            int iRetCode = routerDataInit.loadRouterData();
            if (iRetCode != 0) {
                rglog.error("加载路由静态配置数据到缓存失败");
                return -1;
            }
            //动态统计数据统计在内存中，使用轮询落地落地到数据库，因此启动时从数据库加载动态统计数据到内存
            RouterDataInit routerDataInitMulti = new RouterDataInitMultiDyncData();
            iRetCode = routerDataInitMulti.loadRouterData();
            if (0 != iRetCode) {
                rglog.error("加载多路比例动态统计数据到内存失败");
                return -1;
            }

            //动态统计数据统计在内存中，使用轮询落地落地到数据库，因此启动时从数据库加载动态统计数据到内存
            RouterDataInit routerDataInitSmart = new RouterDataInitSmartDyncData();
            iRetCode = routerDataInitSmart.loadRouterData();
            if (0 != iRetCode) {
                rglog.error("加载智能路由动态统计数据到内存失败");
                return -1;
            }
        } catch (Exception e) {
            rglog.error("智能路由启动数据加载失败！");
            rglog.error(StringUtil.ExceptionToString(e));
            return -1;
        }
        return 0;
    }

    @Override
    protected int bizProcess(String s, int i) {
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        try {
            SmartRouteRequest smartRouteRequest = new SmartRouteRequest();
            //将内部树值取出
            ConvertUtil.convertOutput(smartRouteRequest);
            //参数为空判断
            if (StringUtil.isNullorEmpty(smartRouteRequest.getHeader().getInstId()) ||
                    StringUtil.isNullorEmpty(smartRouteRequest.getHeader().getSrcSysId()) ||
                    StringUtil.isNullorEmpty(smartRouteRequest.getHeader().getChanlId()) ||
                    StringUtil.isNullorEmpty(smartRouteRequest.getTxnGroup())) {
                rglog.error("必须输入机构号<{}>，发起系统<{}>、渠道号<{}>，交易分组<{}>", smartRouteRequest.getHeader().getInstId(),
                        smartRouteRequest.getHeader().getSrcSysId(), smartRouteRequest.getHeader().getChanlId(), smartRouteRequest.getTxnGroup());
                throw new BizException(SmartRouteRspEnums.MSG_VALID_CHECK_ERROR.getRespCode(), SmartRouteRspEnums.MSG_VALID_CHECK_ERROR.getRespDesc());
            }

            xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.SRC_SYS_ID, smartRouteRequest.getHeader().getSrcSysId());
            xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.SYS_SEQ_NUM, smartRouteRequest.getHeader().getTraceNo());
            xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.TRANS_TIME, smartRouteRequest.getHeader().getTransTime());
            xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.TRANS_DATE, smartRouteRequest.getHeader().getTransDate());

            SmartRouteResponse smartRouteResponse = new SmartRouteResponse();
            smartRouteResponse.setHeader(smartRouteRequest.getHeader());
            //输入参数
            RouterReq routerReq = new RouterReq();
            routerReq.setInstId(smartRouteRequest.getHeader().getInstId());
            routerReq.setTransChanlId(smartRouteRequest.getHeader().getChanlId());
            routerReq.setTxnGroup(smartRouteRequest.getTxnGroup());
            routerReq.setTransAmt(smartRouteRequest.getTransAmt());
            routerReq.setDelayedFlag(smartRouteRequest.getDelayedFlag());
            routerReq.setBizCode(smartRouteRequest.getBizCode());
            //根据需要查询的业务代收、代付、鉴权设置对应的交易码
            RouteTxnNumEnum txnNumEnum = RouteTxnNumEnum.getInstanceFromTxnGroup(smartRouteRequest.getTxnGroup());
            if (null == txnNumEnum) {
                rglog.error("交易分组<{}>非法", smartRouteRequest.getTxnGroup());
                throw new BizException(SmartRouteRspEnums.MSG_VALID_CHECK_ERROR.getRespCode(), SmartRouteRspEnums.MSG_VALID_CHECK_ERROR.getRespDesc());
            }
            routerReq.setTxnNum(smartRouteRequest.getHeader().getTxnNum());
            routerReq.setBizType(smartRouteRequest.getHeader().getBizType());
            routerReq.setSrcSysId(smartRouteRequest.getHeader().getSrcSysId());
            routerReq.setPayerInfo(smartRouteRequest.getPayerInfo());
            routerReq.setPayeeInfo(smartRouteRequest.getPayeeInfo());
            //业务处理返回通道信息
            Router router = new Router();
            List<ProdInfoBean> listProdInfoBean = router.choice(routerReq);
            if (null != listProdInfoBean && listProdInfoBean.size() != 0) {
                List<ProdInfo> listProdInfo = new ArrayList<>();
                for (ProdInfoBean prodInfoBean : listProdInfoBean) {
                    ProdInfo prodInfo = new ProdInfo();
                    BeanUtil.beanCopy(prodInfoBean, prodInfo);
                    listProdInfo.add(prodInfo);
                }
                smartRouteResponse.setProdList(listProdInfo);
                smartRouteResponse.setRespCode(SmartRouteRspEnums.TRANS_SUCCESS.getRespCode());
                smartRouteResponse.setRespDesc(SmartRouteRspEnums.TRANS_SUCCESS.getRespDesc());
                ConvertUtil.convertInput(smartRouteResponse);
            } else {
                //路由失败,无可用通道
                throw new BizException(SmartRouteRspEnums.NO_AVAILABLE_DST_CHANNEL_ERROR.getRespCode(),
                        SmartRouteRspEnums.NO_AVAILABLE_DST_CHANNEL_ERROR.getRespDesc());
            }
        } catch (BizException e) {
            try {
                xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.RESP_CODE, e.getCode());
                xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.RESP_DESC, e.getMessage());
            } catch (Exception e1) {
                rglog.error(StringUtil.ExceptionToString(e1));
            }
        } catch (Exception e) {
            rglog.error(StringUtil.ExceptionToString(e));
            try {
                xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.RESP_CODE, SmartRouteRspEnums.TRANS_FAIL.getRespCode());
                xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.RESP_DESC, SmartRouteRspEnums.TRANS_FAIL.getRespDesc());
            } catch (Exception e1) {
                rglog.error(StringUtil.ExceptionToString(e1));
            }
        }
        return 0;
    }

    @Override
    protected int bizTerminate(String s) {
        return 0;
    }
}
